import React from 'react';
import {Form, Input, Button, Message, DatePicker, Icon, Radio, Upload, Modal, Checkbox } from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

let advanceOrderAdd = React.createClass({


  contextTypes: {
    router: React.PropTypes.object
  },

  getInitialState() {
    return {
      loading: false,
      isLook: false,
      imgLook: [],
      priviewVisible: false,
      priviewImage: '',

    }
  },
  
  handleSubmit(e) {
    e.preventDefault();
    let roomId = this.props.location.state;
    let forms = this.props.form.getFieldsValue();
    let isLook ={isLook: this.state.isLook};
    let imgs = {picList: this.getImgList(this.state.imgLook)};
    let startTime = {startTime: Utils.formatDate(forms.startTime)}; //时间格式化
    let checkinTime = {checkinTime: Utils.formatDate(forms.checkinTime)}; //时间格式化
    let reserveTime = {reserveTime: Utils.formatDate(forms.reserveTime)}; //时间格式化
    
    let params = Object.assign({}, forms, roomId, imgs, startTime, checkinTime, reserveTime, isLook);
    console.log(params);
    this.props.form.validateFields((errors, values) => {
      if (!!errors) {
        console.log('Errors in form!!!');
        return;
      }
      this.setState({
        loading: true,
      });
      Utils.sendAjax({
        url: '/room/reserve/add',
        data: JSON.stringify(params),
        callback: (result) => {
          if (result.code === '200') {
            this.handleBack();
          } else {
            this.setState({
              loading: false,
            });
            Message.error(result.message, 10);
          }
        }
      });
    });
  },

  getImgList(img){
    let arry = [];
    if(img){
      img.forEach((item) => {
        let obj = {
          type: item.type,
          url: item.url
        }
        arry.push(obj);
      });
    }
    return arry;
  },

  setImgUrl(img) {
    let newArr = [];
    img.forEach((item, index) => {
      let imgMaps = {
        uid: `card-`+index,
        type: item.type,
        status: 'done',
        url: Utils.apiServer + item.url,
        thumbUrl: Utils.apiServer + item.url,
      };
      newArr.push(imgMaps)
    })
    this.setState({
      imgLook: newArr,
    })
  },

  handleCancel() {
    this.setState({
      priviewVisible: false,
    });
  },

  handleBack() {
    this.context.router.push('/landlord/rentManage/advanceOrder/list');
  },

  handleCheck(e) {
    let newStr = e.target.checked ? 1 : 0;
    this.setState({
      isLook: newStr
    })
  },

  deleteImg(file) {
    let newArr = [];
    let imgs = this.state.imgLook;
    imgs.forEach((img, index)=> {
      if (img.uid !== file.uid) {
        newArr.push(img)
      }
    })
    this.setState({
      imgLook: newArr
    })
    this.setImgUrl(newArr);
  },

  render() {
    const _me = this;
    const { getFieldProps } = this.props.form;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 6},
    };

    let card = {
      name: 'file',
      data: {nid: 'card'},
      listType: 'picture-card',
      action: Utils.apiServer + '/img/uploadifySave',
      multiple: true,
      fileList: this.state.imgLook,
      beforeUpload(file) {
        console.log(file)
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isSize = file.size > 5242880 ? false : true;
        if (!isJPG) {
          Message.error('只能上传jpg、png图片文件哦！', 10);
          return isJPG
        }
        if (!isSize) {
          Message.error('你选择的图片过大！', 10);
          return isSize
        }
      },
      onChange: function (files) {
        let imgList = _me.state.imgLook;
        let status = files.file.status
        if (status == 'done') {
          let file = files.file;
          let img = file.response ? file.response.data : '';
          imgList.push({type: 'card', url: img});
          _me.setImgUrl(imgList);
        }
      },
      onPreview: (file) => {
        let arry = file.url.split('.')
        _me.setState({
          priviewImage: arry[0]+'_big.'+arry[1],
          priviewVisible: true,
        });
      },
      onRemove: (file) => {
        _me.deleteImg(file)
      }
    };

    return (
      <div className="inner-content">

        <Form horizontal form={this.props.form}>
          {/*<FormItem
            {...formItemLayout}
            label="房源地址">
            <Input />
          </FormItem>*/}
          <FormItem
            {...formItemLayout}
            label="租客姓名">
            <Input {...getFieldProps('renterName', {rules: [{ required: true,  message: '租客姓名不可为空' }]})}
              placeholder="租客姓名"/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="租客性别">
            <RadioGroup {...getFieldProps('renterSex', {initialValue: '男'})}>
              <Radio value="男">男</Radio>
              <Radio value="女">女</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="联系电话">
            <Input {...getFieldProps('renterPhone', {rules: [{ required: true,  message: '联系电话不可为空' },
              {validator: Utils.phone}]})}
              placeholder="联系电话"/>
          </FormItem>

          <FormItem
            {...formItemLayout}
            label="身份证号">
            <Input {...getFieldProps('renterNo',
              {rules: [{ required: true, message: '身份证号不可为空' },
                        {validator: Utils.card}]})} placeholder="身份证号"/>
          </FormItem>

          <FormItem
            className="order-date"
            {...formItemLayout}
            label="预约入住时间">
            <DatePicker {...getFieldProps('checkinTime',
              {rules: [{ required: true, type: 'date', message: '预约入住时间不可为空' }]})}
            />
          </FormItem>
          <FormItem
            className="order-date"
            {...formItemLayout}
            label="预订时间">
            <DatePicker {...getFieldProps('reserveTime',{initialValue: Utils.formatDate(new Date())})}/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="订金">
            <Input {...getFieldProps('reserveAmount', {initialValue: '0.00',
              rules: [{required: true, message: '订金不可为空'},{validator: Utils.floatNum}]})} addonAfter="元" placeholder="订金"/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="租金">
            <Input {...getFieldProps('rent', {initialValue: '0.00',
              rules: [{ required: true, message: '租金不可为空' }, {validator: Utils.floatNum}]})} addonAfter="元/月"  placeholder="租金"/>
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="是否看房">
            <Checkbox {...getFieldProps('isLook', {initialValue: 0})}
              onChange={this.handleCheck}>看房</Checkbox>
          </FormItem>
          {
          //   <FormItem className="pic-box"
          //   labelCol={{span: 4}}
          //   wrapperCol={{span: 20}}
          //   label="上传图片">
          //   <Upload  {...card}>
          //     <div className="img-icon">
          //       <Icon type="plus"/>
          //       <h5>添加图片</h5>
          //     </div>
          //   </Upload>
          // </FormItem>
          }
          
          <FormItem
            {...formItemLayout}
            label="备注">
            <Input type="textarea" {...getFieldProps('remark')} placeholder="备注信息"/>
          </FormItem>
          <FormItem
            wrapperCol={{ span: 10, offset: 4 }} style={{ marginTop: 24 }}>
            <Button type="primary" loading={this.state.loading} onClick={this.handleSubmit}>预订</Button>
            <Button style={{ marginLeft: 20 }} onClick={this.handleBack}>返回</Button>
          </FormItem>
        </Form>
        <Modal visible={this.state.priviewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="预览" src={this.state.priviewImage} width="500"/>
        </Modal>
      </div>
    );
  }
});
advanceOrderAdd = Form.create()(advanceOrderAdd);
export default advanceOrderAdd